import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';

export default defineConfig(({ mode }) => {
  const isLib = mode === 'lib';

  return {
    plugins: [vue()],
    build: isLib
      ? {
          lib: {
            entry: {
              dict: './src/main.ts',
            },
            name: 'DictComponents',
            fileName: (format, entryName) => `${entryName}.${format}.js`,
            formats: ['es'],
          },
          rollupOptions: {
            external: ['vue'],
            output: {
              globals: {
                vue: 'Vue',
              },
              exports: 'named',
              // 自定义文件输出路径
              assetFileNames: (assetInfo) => {
                if (!assetInfo.name) {
                  return `assets/[name].[hash].[ext]`;
                }
                const info = assetInfo.name.split('.');
                const ext = info[info.length - 1];
                if (/\.(map)$/.test(assetInfo.name)) {
                  return `maps/[name].[hash].${ext}`;
                }
                return `assets/[name].[hash].${ext}`;
              },
              chunkFileNames: (chunkInfo) => {
                // 根据chunk内容分类到不同目录
                if (chunkInfo.name?.includes('dictStore')) {
                  return `store/[name].js`;
                }
                if (chunkInfo.name?.includes('selectTagAntd')) {
                  return `components/[name].js`;
                }
                if (chunkInfo.name?.includes('selectTagVue')) {
                  return `components/[name].js`;
                }
                return `utils/[name].js`;
              },
              entryFileNames: (chunkInfo) => {
                return `[name].js`;
              },
            },
          },
          outDir: 'dist',
          sourcemap: true,
          cssCodeSplit: false,
        }
      : {
          outDir: 'dist',
          sourcemap: true,
        },
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
  };
});
